﻿using System;
using System.Collections.Generic;
using System.Linq;
using cludg.Repository.NHibernate.Sessions;
using cludg.Domain.Content.Stories;
using cludg.Domain.Users;
using NHibernate.Linq;
using cludg.Repository.Content;

namespace cludg.Web.RateContentModule.Repository.NHibernate
{
	public class RateRepository : IRateRepository
	{
		protected readonly INHibernateSessionController SessionController;
		protected readonly IContentRepository<Story> StoryRepository;

		public RateRepository(
			INHibernateSessionController sessionController,
			IContentRepository<Story> storyRepository)
		{
			SessionController = sessionController;
			StoryRepository = storyRepository;
		}

		protected IQueryable<Domain.RateHistory> All
		{
			get
			{
				return
					SessionController.Current.Linq<Domain.RateHistory>(
						SessionController.Current.CreateCriteria<Domain.RateHistory>().SetCacheable(true));
			}
		}

		public Domain.RateHistory GetForUser(User user, Story story)
		{
			return AllForStory(story).FirstOrDefault(x => x.UserId == user.Id);
		}

		public bool HasForUser(User user, Story story)
		{
			return AllForStory(story).Any(x => x.UserId == user.Id);
		}

		public IEnumerable<Domain.RateHistory> AllForStory(Story story)
		{
			return All.Where(x => x.StoryId == story.Id);
		}

		public void Add(Domain.RateHistory rate)
		{
			try
			{
				SessionController.Current.Save(rate);
			}
			catch (Exception)
			{
				SessionController.Reset();
				throw;
			}
		}

		public void Save(Domain.RateHistory rate)
		{
			try
			{
				SessionController.Current.Update(rate);
			}
			catch (Exception)
			{
				SessionController.Reset();
				throw;
			}
		}
	}
}